package com.saltedfish.tool.dialog;

import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.saltedfish.tool.R;
import com.saltedfish.tool.model.SmallTable;
import com.saltedfish.tool.ui.flag.adapter.SelectDayAdapter;
import com.saltedfish.tool.util.DateUtils;
import com.saltedfish.tool.util.UIUtils;
import com.saltedfish.tool.view.calendar.CalendarView;
import com.saltedfish.tool.view.calendar.Day;
import com.saltedfish.tool.view.calendar.DayManager;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import cn.droidlover.xdroidmvp.base.SimpleListener;
import cn.droidlover.xdroidmvp.popwindow.DialogHelper;
import cn.droidlover.xdroidmvp.util.ToastUtils;

public class UIDateDialogs extends DialogHelper {

    @BindView(R.id.tv_calender_month)
    TextView tv_calender_month;
    @BindView(R.id.calenderMonth)
    LinearLayout calenderMonth;
    @BindView(R.id.tvBack)
    ImageView tvBack;
    @BindView(R.id.tvDateTitle)
    TextView tvDateTitle;
    @BindView(R.id.calendar)
    CalendarView calendar;

    @BindView(R.id.mRecyclerView)
    RecyclerView mRecyclerView;

    @BindView(R.id.linear_date_end)
    LinearLayout linear_date_end;

    Date curDate;

    Calendar cal;

    //0代表开始时间 1，是结束时间
    private int type;

    SimpleDateFormat formatter ;
    private SimpleDateFormat formatterDay = new SimpleDateFormat("yyyy-MM-dd");

    //选中时间
    private String putDate;
    //当天时间
    private String dayDate;
    private SelectDayAdapter flagAdapter;
    private SmallTable subFlagModel;

    public UIDateDialogs(Activity context) {
        super(context, R.style.AlertDialogStyle);
        this.mContext = context;

        setFullWidthScreen();
        setGravity(Gravity.BOTTOM);
        setAnimSet(R.style.popRightPopAnim);

    }

    @Override
    protected int getLayoutId() {
        return R.layout.dialog_ui_dates;
    }


    public void updateDate(int type, SmallTable subFlagModel) {
        this.type = type;
        this.subFlagModel = subFlagModel;
//        XLog.e("-subFlagModel--->>"+subFlagModel.toString());
        if(type == 0){
            dayDate = DateUtils.getStringDateShort();
            tvDateTitle.setText("开始日期");
            linear_date_end.setVisibility(View.GONE);
            if(!TextUtils.isEmpty(subFlagModel.startTime)){
                putDate = subFlagModel.startTime;
            }else {
                putDate = dayDate;
                subFlagModel.startTime = dayDate;
            }
            String startTime = DateUtils.strToDateStr2(putDate);
            initShowDateView(startTime);

        }else {
            linear_date_end.setVisibility(View.VISIBLE);
            tvDateTitle.setText("结束日期");
            initData();
            if(!TextUtils.isEmpty(subFlagModel.endTime)){
                putDate = subFlagModel.endTime;
               // putDate = formatterDay.format(subFlagModel.endTime);
               // String date = formatter.format(subFlagModel.endTime);

                String endTime = DateUtils.strToDateStr2(subFlagModel.endTime);
                initShowDateView(endTime);

            }else {
                this.putDate = "";
            }
        }

    }


    @Override
    protected void initView() {
        cal = Calendar.getInstance();
        formatter = new SimpleDateFormat("yyyy年MM月");
        //获取当前时间
        curDate = cal.getTime();
        String strDate = formatter.format(curDate);

        if (!TextUtils.isEmpty(strDate)) {
            tv_calender_month.setText(strDate);
        }

        calendar.setCalendar(cal);
        initCalendar();
        initSelectCalendar(calendar);

        tvBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                dismiss();
            }
        });

        calendar.setOnSelectChangeListener(new CalendarView.OnSelectChangeListener() {
            @Override
            public void selectChange(CalendarView calendarView, Date date) {
                String defaultStartDate = formatterDay.format(date); //格式化前一天
                int index = DateUtils.compareEqualsDate(defaultStartDate, "");
                if(type == 0){
                    if(index == 1){
                        ToastUtils.showMessage(mContext,"请选择今天或之后的日期");
                    }else {
                        putDate = defaultStartDate;
                        initSelectCalendar(calendarView);
                        initData();
                    }
                }else {
                    int indexDay = DateUtils.compareEqualsDate(defaultStartDate, subFlagModel.startTime);
                    if(indexDay == 0) {
                        putDate = defaultStartDate;
                        initSelectCalendar(calendarView);
                        initData();
                    }else {
                        int Day = DateUtils.compareEqualsDate(subFlagModel.startTime, "");
                        if(Day == 1){
                            ToastUtils.showMessage(mContext,"请选择今天或之后的日期");
                        }else {
                            ToastUtils.showMessage(mContext,"请选择开始日期之后的日期");
                        }

//                        if(!TextUtils.isEmpty(subFlagModel.status)){
//                            if(subFlagModel.status.equals("noStart")){
//                                 ToastUtils.showMessage(mContext,"请选择开始日期之后的日期");
//                            }else {
//                                ToastUtils.showMessage(mContext,"请选择今天或之后的日期");
//                            }
//                        }else {
//                            int Day = DateUtils.compareEqualsDate(subFlagModel.startTime, "");
//                            if(Day == 1){
//                                ToastUtils.showMessage(mContext,"请选择今天或之后的日期");
//                            }else {
//                                ToastUtils.showMessage(mContext,"请选择开始日期之后的日期");
//                            }
//                        }
                    }
                }
            }
        });

        calenderMonth.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                initMonthView();
            }
        });

    }


    /**
     * 初始化界面
     */
    private void initCalendar() {
        ViewGroup.LayoutParams mParamImage = calendar.getLayoutParams();
        int index = cal.getActualMaximum(Calendar.WEEK_OF_MONTH) + 1;
        int imageHeight = index * UIUtils.dip2px(mContext, 50);
        mParamImage.height = imageHeight;
        calendar.setLayoutParams(mParamImage);

    }

    /**
     * 初始化选择后的日历界面
     */
    private void initSelectCalendar(CalendarView calendarView) {
        calendarView.setOnDrawDays(new CalendarView.OnDrawDays() {
            @Override
            public boolean drawDay(Day day, Canvas canvas, Context context, Paint bgPaint) {
                if (!day.dateText.equals("-1")) {
                    Typeface font = Typeface.create(Typeface.DEFAULT, Typeface.NORMAL);
                    bgPaint.setTypeface(font);
                    bgPaint.setFakeBoldText(false);

                    if(type == 0){
                        int dayIndex = DateUtils.compareEqualsDate(day.dateText, dayDate);
                     //   XLog.e("test", day.dateText + "----111----day.dateText-->>" + putDate+"----"+dayDate);
                        if(dayIndex == 1){
                            day.textClor = 0xffCCCCCC;
                        }else {
                            int index = DateUtils.compareEqualsDate(day.dateText, putDate);
                            if(index == -1){
                                day.textClor = 0xffffffff;
                                bgPaint.setStyle(Paint.Style.FILL_AND_STROKE);  //空心
                                Typeface fonts = Typeface.create(Typeface.DEFAULT, Typeface.BOLD);
                                bgPaint.setTypeface(fonts);
                                bgPaint.setFakeBoldText(true);
                                bgPaint.setColor(mContext.getResources().getColor(R.color.color_3097FF));
                                bgPaint.setStrokeWidth(15f);       //画笔宽度
                                //绘制空心圆背景
                                canvas.drawCircle(day.width/2, day.height/2 , 50, bgPaint);
                            }
                        }
                    }else {

                        int days = DateUtils.compareEqualsDate(day.dateText, subFlagModel.startTime);
                        int dayShow = DateUtils.compareEqualsDate(subFlagModel.startTime, "");

                        if(days == -1){
                            if(dayShow == 1){
                                day.textClor = 0xffCCCCCC;
                            }else {
                                day.textClor = 0xff3097FF;
                            }

                        }else {
                            int dayIndex = DateUtils.compareEqualsDate(day.dateText, dayDate);
                            // XLog.e("test", day.dateText + "----111----day.dateText-->>" + putDate+"----"+dayIndex+"===="+dayDate);
                            if(dayIndex == -1){
                                int index = DateUtils.compareEqualsDate(day.dateText, putDate);
                                if(index == -1){
                                    day.textClor = 0xffffffff;
                                    bgPaint.setStyle(Paint.Style.FILL_AND_STROKE);  //空心
                                    Typeface fonts = Typeface.create(Typeface.DEFAULT, Typeface.BOLD);
                                    bgPaint.setTypeface(fonts);
                                    bgPaint.setFakeBoldText(true);
                                    bgPaint.setColor(mContext.getResources().getColor(R.color.color_3097FF));
                                    bgPaint.setStrokeWidth(15f);       //画笔宽度
                                    //绘制空心圆背景
                                    canvas.drawCircle(day.width/2, day.height/2 , 50, bgPaint);
                                }else {
                                    day.textClor = 0xff333333;
//                                    if(dayShow == 1){
//                                         day.textClor = 0xffCCCCCC;
//                                    }else {
//                                    //  day.textClor = 0xff3097FF;
//                                     }
                                }
                                //比今天小的时间至灰色
                            }else if(dayIndex == 1){
                                day.textClor = 0xffCCCCCC;
                            }else {
                                int index = DateUtils.compareEqualsDate(day.dateText, putDate);
                                if(index == -1){
                                    day.textClor = 0xffffffff;
                                    bgPaint.setStyle(Paint.Style.FILL_AND_STROKE);  //空心
                                    Typeface fonts = Typeface.create(Typeface.DEFAULT, Typeface.BOLD);
                                    bgPaint.setTypeface(fonts);
                                    bgPaint.setFakeBoldText(true);
                                    bgPaint.setColor(mContext.getResources().getColor(R.color.color_3097FF));
                                    bgPaint.setStrokeWidth(15f);       //画笔宽度
                                    //绘制空心圆背景
                                    canvas.drawCircle(day.width/2, day.height/2 , 50, bgPaint);
                                }
                            }
                        }
                    }
                }
                return false;
            }

            @Override
            public void drawDayAbove(Day day, Canvas canvas, Context context, Paint paint) {
                if (!day.dateText.equals("-1")) {

                    int index = DateUtils.compareEqualsDate(day.dateText, subFlagModel.startTime);
                    if (index == -1 && type == 1) {
                        int dayShow = DateUtils.compareEqualsDate(subFlagModel.startTime, "");
//                        XLog.e("test", subFlagModel.startTime + "----111----day.dateText-->>" + putDate+"----"+dayShow);
                 //       XLog.e("test", day.dateText + "----222----day.dateText-->>" + putDate+"----"+dayShow);
                        if(dayShow == 1){
                            day.textClor = 0xffCCCCCC;
                        }else {
                            day.textClor = 0xff3097FF;
                        }
                        DayManager.drawWorkText(dayShow,day, canvas, paint);
                    }
                }
            }
        });

    }


    private  UIMonthDialog uiMonthDialog ;

    private void initMonthView() {
         String month = tv_calender_month.getText().toString();
        if(uiMonthDialog == null){
            uiMonthDialog = new UIMonthDialog(mContext);
            uiMonthDialog.setSimpleListener(new SimpleListener() {
                @Override
                public void onClick(String strDate) {
                    initShowDateView(strDate);

//                    int index = DateUtils.compareEqualsMonth(strDate, "");
//                    if(index == 1){
//                        ToastUtils.showMessage(mContext,"请选择当月或之后的月份");
//                    }else {
//                       // initData();
//                        initShowDateView(strDate);
//                    }
                }

            });
        }
        uiMonthDialog.updateDate(month);
        uiMonthDialog.show();

    }


    /**
     * 日期界面展示
     */
    private void initShowDateView(String strDate) {
        tv_calender_month.setText(strDate);
        try {
            Date newTime = formatter.parse(strDate);
            cal.setTime(newTime);
            calendar.setCalendar(cal);
            initCalendar();
            initSelectCalendar(calendar);

        } catch (ParseException e) {
            e.printStackTrace();
        }

    }

    List<Integer> selectList;

    private int selectPosition = 10;

    /**
     * 初始化常用天数
     */
    @Override
    protected void initData() {
        selectPosition = 10;
        if(type == 1){
            selectList = new ArrayList<>();
            selectList.add(7);
            selectList.add(30);
            selectList.add(100);
            selectList.add(365);
            selectList.add(500);
            selectList.add(1000);

            flagAdapter = new SelectDayAdapter(selectList,mContext);
            flagAdapter.setListener(new SimpleListener() {

                @Override
                public void onClick(int index) {
                    selectPosition = index;
                    putDate = DateUtils.getNextDay(subFlagModel.startTime,selectList.get(index)-1);
//                    XLog.e("------>>"+putDate);
                    String date = DateUtils.strToDateStr2(putDate);
//                    cal = Calendar.getInstance();
//                    cal.add(Calendar.DATE, );
//                    Date selectDayDate = cal.getTime();
//                    putDate = formatterDay.format(selectDayDate);
//                    String date = formatter.format(selectDayDate);
                    initShowDateView(date);
                }
            });
            flagAdapter.setSelectPosition(selectPosition);
            mRecyclerView.setHasFixedSize(true);
            mRecyclerView.setLayoutManager(new GridLayoutManager(mContext,3));
            mRecyclerView.setAdapter(flagAdapter);
        }

    }


    @Override
    protected void dialogDismiss() {
        dismiss();
    }

    @Override
    public void dismiss() {

        if(type == 0){
            subFlagModel.startTime = putDate;
        }else {
            subFlagModel.endTime = putDate;
        }
        if (listener != null) {
            listener.onDateClick(subFlagModel);
        }

        mContext.getWindow().setStatusBarColor(mContext.getResources().getColor(R.color.color_white));
        initView();
        initData();
        super.dismiss();

    }

    private SimpleDateListener listener;

    public static class SimpleDateListener{
        void onDateClick(SmallTable subFlagModel) { }
    }

    public void setListener(SimpleDateListener listener) {
        this.listener = listener;
    }
}
